import { NodeItem } from '@/types/node'
import { injectable, Service, mutex } from './service'
import { appDataDir, join } from '@tauri-apps/api/path'
import { exists, readTextFile, writeTextFile, mkdir } from '@tauri-apps/plugin-fs'

@injectable
export default class NodeService extends Service {
  inner_nodes = [
    {
      type: 'const',
      id: 'const',
      name: '常量',
      outputs: [{
        type: 'number',
        name: 'value'
      }],
      inputs: [],
      script: ''
    },
    {
      type: 'debug',
      id: 'debug',
      name: 'Debug',
      outputs: [{
        type: 'any',
        name: 'o'
      }],
      inputs: [{
        type: 'any',
        name: 'i'
      }],
      script: ''
    }
  ]

  nodes = [] as NodeItem[]

  constructor () {
    super()
    appDataDir().then(async dir => {
      if (!await exists(dir)) {
        mkdir(dir)
      }
    })
  }

  @mutex
  async load () {
    if (this.nodes.length > 0) {
      return this.nodes
    }
    const filePath = await join(await appDataDir(), 'nodes.json')
    if (!await exists(filePath)) {
      return []
    }
    const txt = await readTextFile(filePath)
    this.nodes = JSON.parse(txt)
    return this.nodes
  }

  async save (nodes: NodeItem[]) {
    const filePath = await join(await appDataDir(), 'nodes.json')
    await writeTextFile(filePath, JSON.stringify(nodes))
    this.nodes = nodes
  }
}
